#!/usr/bin/python

import sys
import json
import _thread
import socket
import argparse

class client:

    BUFFER_SIZE = 1024

    def __init__(self):
        if len(sys.argv) < 4:
            print("Use: python3 client.py [server_ip] [server_port] [username]")
            exit()
        self.TCP_IP = sys.argv[1]
        self.TCP_PORT = int(sys.argv[2])
        self.username = sys.argv[3]
        
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        try:
            self.s.connect((self.TCP_IP, self.TCP_PORT))
            self.run()
        except socket.error as msg:
            print(msg)
            self.s.close()
            exit()

    def helo(self):
        heloJson = '{"username":"'+self.username+'"}'
        helo = b'\x01' + bytes('{"username":"'+self.username+'"}', 'utf-8')
        self.s.send(helo)
        data = self.s.recv(self.BUFFER_SIZE)[1:]
        self.locations = json.loads(data.decode('utf-8'))['locations']
        self.sessions = json.loads(data.decode('utf-8'))['sessions']

    def create(self, datetime, location, resources):
        self.helo()
        session['users'][0] = self.username
        session['datetime'] = datetime
        for index, location in self.locations:
            print(index+' => '+location)
        locationId = input('Location: ')
        session['session_id'] = locationId
        session['resources']['tabak'] = int(input('Tabak? (0 or 1)')) == 1
        session['resources']['filter'] = int(input('Filter? (0 or 1)')) == 1
        session['resources']['papes'] = int(input('Papes? (0 or 1)')) == 1
        session['resources']['lighter'] = int(input('Lighter? (0 or 1)')) == 1
        create = b'\x01' + bytes(json.dumps(session), 'utf-8')
        self.s.send(create)

    def join(self):
        for session in self.sessions:
            print("Id: "+str(session['id']))
            print('Day: '+session['datetime'][0:10])
            print('Time: '+session['datetime'][11:-5])
            
            print('Location: '+session['location'])
            users = ""
            for user in session['users']:
                users += user+", "
            print("Users: "+users[:-2])
            print('----------------------------------------------')
        sessionId = input('Session Id: ')
        session['session-id'] = int(sessionId)
        session['resources']['tabak'] = int(input('Tabak? (0 or 1)')) == 1
        session['resources']['filter'] = int(input('Filter? (0 or 1)')) == 1
        session['resources']['papes'] = int(input('Papes? (0 or 1)')) == 1
        session['resources']['lighter'] = int(input('Lighter? (0 or 1)')) == 1
        join = b'\x05' + bytes(json.dumps(session), 'utf-8')
        self.s.send(join)




    def leave(self):
        for session in self.sessions:
            if self.username in session['users']:
                print(index+' => '+session)
        sessionIndex = input('Session: ')
        join = b'\x06' + bytes(json.dumps(self.sessions[sessionIndex]), 'utf-8')
        self.s.send(join)
    
    def getUpdates(self, ksdbfkas):
        while True:
            rawData = self.s.recv(self.BUFFER_SIZE)
            if rawData[0] == 4:
                data = rawData[1:]
                this.sessions = json.loads(data.decode('utf-8'))['sessions']
            else:
                print('Warning: Packet has no update-signature')
                print('Signature: '+str(rawData[0]))
                print('Packet: '+rawData[1:])

    def run(self):
        self.helo()
        # new thread listen to updates
        _thread.start_new_thread(self.getUpdates, (self,))
        try:
            while True:
                command = input("Command: ")
                if command == 'j':
                        self.join()
                elif command == 'l':
                        self.leave()
                elif command == 'c':
                    self.create()
                else:
                    print('---------------')
                    print('Commands:')
                    print('\tl => leave')
                    print('\tj => join')
                    print('\tc => create')
                    

        except KeyboardInterrupt:
            self.s.close()
            print('See ya ʕ•ᴥ•ʔ')

me = client()
